
from flask import Flask, send_file, request,jsonify

from src.chat.chat import chat_main
from src.operate_project.git_project import git_main
from src.operate_project.delete_project import del_file
from src.parse_project.main import main, read_file
from flask_cors import CORS,cross_origin

from flask import send_file, jsonify, request, abort
from flask_cors import cross_origin
import os
from werkzeug.utils import safe_join

from flask import Flask, request, jsonify

app = Flask(__name__)
CORS(app)

from flask_cors import CORS

app = Flask(__name__)
# 允许来自 Vue 应用的跨域请求
CORS(app, resources={r"/chat": {"origins": "http://localhost:5173"}})
#
# @app.route('/data', methods=['POST'])
# def handle_git_data():
#     data = request.json
#     if data.get('git'):
#         # 模拟处理 git 数据的逻辑
#         return jsonify({"code": "200", "message": "Git data processed", "data": data}), 200
#     else:
#         return jsonify({"code": "400", "message": "Bad request"}), 400
#
# if __name__ == '__main__':
#     app.run(debug=True)
#
#
#

# 下载文件
@app.route('/download', methods=['GET'])
@cross_origin()  # 确保允许跨域请求
def download_specific_file():
    # 文件相对路径
    file_name = "report.md"

    # 构建文件的安全路径，避免路径遍历攻击
    file_path = safe_join("./", file_name)

    # 检查文件是否存在
    if not os.path.exists(file_path):
        # 如果文件不存在，返回 404 错误
        abort(404, description=f"File {file_name} not found")

    try:
        # 如果文件存在，发送文件
        return send_file(file_path, as_attachment=True)
    except Exception as e:
        # 处理文件发送过程中可能出现的错误
        return jsonify({"code": "500", "message": f"Error downloading file: {str(e)}"}), 500


# 添加git
from flask_cors import CORS, cross_origin

# 添加git，确保跨域请求
@app.route('/data', methods=['POST'])
@cross_origin()  # 允许跨域请求
def data():
    print(f"1111")
    jsondata = request.json  # 获取JSON数据
    path = r'./java'
    del_file(path)
    data = jsondata.get("git")
    if data:
        # with open('example.txt', 'w') as file:
        #     file.write(data)
        git_main(data)
        # directory = read_file("./java", " ")
        # print(directory)
        print("1")
        main()
        print("2")
        return jsonify({'code': "200", "message": "Git data processed"})
    else:
        return jsonify({'code': "400", "message": "Invalid data"})


# https://gitee.com/dromara/hutool.git
# https://atomgit.com/so_love_bang/backend


# 聊天
@app.route('/chat', methods=['POST', 'OPTIONS'])
@cross_origin()  # 确保允许跨域请求
def chat_data():
    if request.method == 'OPTIONS':
        return jsonify({'message': 'CORS preflight passed'}), 200

    data = request.json
    question_git = data.get("data")
    resdata = chat_main(question_git)
    return jsonify({'data': resdata.content})


# 获取当前可下载的仓库链接
@app.route('/getgitwarehouse', methods=['GET'])
@cross_origin()  # 允许跨域请求
def get_gitwarehouse():
    file_path = 'example.txt'

    # 检查文件是否存在
    if not os.path.exists(file_path):
        return jsonify({'code': '404', 'message': 'File not found'}), 404

    try:
        with open(file_path, 'r') as file:
            warehouse_urls = file.readlines()

            # 检查文件是否为空
            if not warehouse_urls:
                return jsonify({'code': '204', 'message': 'No data available'}), 204

            # 去除换行符和多余的空白字符
            warehouse_urls = [url.strip() for url in warehouse_urls]

        return jsonify({'code': '200', 'data': warehouse_urls}), 200

    except Exception as e:
        # 处理读取文件时的异常
        return jsonify({'code': '500', 'message': f'Error reading file: {str(e)}'}), 500


# 下载仓库报告的路由
@app.route('/downloadRepo', methods=['GET'])
@cross_origin()  # 确保允许跨域请求
def download_repo():
    # 你要下载的是根目录下的 report.md 文件
    report_path = 'report.md'  # 直接指向根目录下的文件

    # 检查文件是否存在
    if not os.path.exists(report_path):
        return jsonify({"code": "404", "message": "Report not found"}), 404

    try:
        # 返回报告文件作为附件下载
        return send_file(report_path, as_attachment=True)
    except Exception as e:
        return jsonify({"code": "500", "message": f"Error downloading report: {str(e)}"}), 500


if __name__ == '__main__':
    app.run(debug=True)

# from flask import Flask
#
# from demo import main_run
#
# app = Flask(__name__)
# app.config['JSON_AS_ASCII']=False
#
# @app.route('/hello',methods=['GET','POST'])
# def hello_world():  # put application's code here
#     return "main_run()"
#
#
# if __name__ == '__main__':
#     # app.run(debug=True)
#     app.run(debug=True, host='127.0.0.1', port=5000)
